package com.taptech.doufu.umeng;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.bridge.JSCallback;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.activity.me.PhoneLoginActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.dialog.AppGlobalDialog;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.weex.http.TFHttpError;
import com.taptech.doufu.weex.http.TFHttpResponse;
import com.taptech.doufu.weex.http.TFHttpUtil;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMCustomInterface;
import com.umeng.umverify.listener.UMPreLoginResultListener;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;
import com.umeng.umverify.view.UMAuthRegisterViewConfig;
import com.umeng.umverify.view.UMAuthUIConfig;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.functions.Action1;

public class UVerifyManager {
//    private static final String secret = "qGUDWNKxhsKzOSfTB65swfiNS4raH7DkAY2VOqxsXmrTIQENw07dQOJCNBg6bDceQMwezT5Sy8N16J0zJlj5dLnlPsEYZX5kq7NLFf+zd2kSohbpcNqI71mIoKXlo0XXlHqGkCxJuiXhHtNRfPFUH6if80G2AX+aOuHszG0Jc3RJVpOwTXfncs8foFBDDVofPtbmPo1zXfupDyFwyqPS1Ke1jl39/jDoUiK7drz5R2tKx/BE+gOvX8KWmjCeO1vtY8yniXkHfgAMpPHVA5DsVsk8UqCvrIsR";
//    private static final String secret = "sIVM7BKtA39cth7Xxeqj8DTwJOEH4eNl3aBKlM5bYr+IoXqtuAX/ZDpUw8B0TLnT621NrdhdfavHeK7sLmtDwcYr+2Xu8U1gcu4GG1UZYBPRT7FDyHI6v7Xzwnjk1vkWTM09m8Htflv8YCQ+FFq0X/mKW1iBVwvJUJvhjV/n84gyWyPqhqZRJQaTxVD4autN7VRQ39445c/7bp8bf2FCV8lDNrn+g49XWEzjdcWHlywmYuvW6eGI0v1BffYGk+Qp32sVwH5MuxhTns94CBURtv5TXppIejf3tBdJY/qvFPA2TESS8rICt5zM1j4KnS5S";
    private static final String SECRET = "Zw5ZjWfp30ccvDR+cvsmY5334ZzNmtwuFnTfYxgjU6vbTerLFi0P0TIxdbqdEJnX/le1d6Uwhx0xOYXC9zwopmP2uOp5I3mbqu4xLwOskBnCwSvu9rYMTdqyZ2Y8XrKOc0TeiDL2SH8nF+5ICt5v4YLEVDnfNEZaeQJoaHBDM1L+rNbe6UqKwp+yxH7x47CAhMRWDZ1U2rvFriiNs4e0g18cjmvb40g7pSm0phgY7/nAmCCDgilW7fYoADcFdwbrTAnYZvWJydjeHu/sCttCarkw+YsrvQimGXYn1AGIMcLxrN0b8t5Vlq5Qy7RcchwR";

    private final static String SP_KEY_FIRST_OPEN_APP = "first_open_app";
    private Context mContext;
    private boolean isLoading = false;
    private JSCallback callback;
    private UVerifyManager() {
        mContext = WeMediaApplication.applicationContext;
    }

    private static class Inner{
        private static UVerifyManager instance = new UVerifyManager();
    }

    public static UVerifyManager getInstance() {
        return Inner.instance;
    }

    private UMVerifyHelper umVerifyHelper;

    private static Handler mHandler = new Handler();

    /**
     * UMTokenResultListener 获取token和拉起授权页的监听回调
     */
    private UMTokenResultListener mTokenListener = new UMTokenResultListener() {
        @Override
        public void onTokenSuccess(final String ret) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    UMTokenRet tokenRet = null;
                    try {
                        tokenRet = JSON.parseObject(ret, UMTokenRet.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (tokenRet != null) {
                        if (!("600001").equals(tokenRet.getCode())) {
                            login(tokenRet.getToken());
                        }else{
                            if (callback != null) {
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("res", true);
                                callback.invoke(map);
                                callback = null;
                            }
                        }
                    }
                    AppGlobalDialog.dismissDialog();
                }
            });
        }

        @Override
        public void onTokenFailed(final String ret) {
            Log.e("Umeng", "获取token失败：" + ret);

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    UMTokenRet tokenRet = null;
                    try {
                        tokenRet = JSON.parseObject(ret, UMTokenRet.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (tokenRet != null && !("700000").equals(tokenRet.getCode())) {
                        umVerifyHelper.hideLoginLoading();
                        umVerifyHelper.quitLoginPage();
                        jumpOtherLogin(tokenRet.getMsg());
                    }
                }
            });
        }
    };

    private void jumpOtherLogin(String msg) {
        if (isLoading) {
            AppGlobalDialog.dismissDialog();
            isLoading = false;
            if (callback != null) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("res", false);
                map.put("msg", msg);
                callback.invoke(map);
                callback = null;
            }else{
                PhoneLoginActivity.Companion.startActivity(mContext);
//                SimpleWeexActivity.startActivity(mContext,"vue/login/TFLoginRegister.js", Intent.FLAG_ACTIVITY_NEW_TASK);
            }
        }
    }




    private void login(String token) {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        TFHttpUtil.requestGet("http://api.doufu.la/member/u_verify_login", map, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                umVerifyHelper.hideLoginLoading();
                if (json != null && json.containsKey("status")) {
                    int status = json.getInteger("status");
                    if (status == 0) {
                        String data = json.getString("data");
                        Toast.makeText(mContext,"登录成功",Toast.LENGTH_LONG).show();
                        AccountService.setAccountData(data,null);
                        QLXNotificationCenter.getInstance().postNotify("kTFUserDidLoginCompleteNotification",null);
                        umVerifyHelper.quitLoginPage();
                    }else{
                        Toast.makeText(mContext,"登录失败，请重试",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(mContext,"登录失败，请重试",Toast.LENGTH_LONG).show();
                }
            }
        });
    }


    private boolean initVerify() {
        /**
         * 获取UMVerifyHelper实例，设置秘钥信息
         */
        if (umVerifyHelper == null) {
            umVerifyHelper = UMVerifyHelper.getInstance(mContext, mTokenListener);
            umVerifyHelper.setAuthSDKInfo(SECRET);
            umVerifyHelper.setAuthListener(mTokenListener);
            umVerifyHelper.accelerateLoginPage(5000, new UMPreLoginResultListener() {
                @Override
                public void onTokenSuccess(final String vendor) {

                }

                @Override
                public void onTokenFailed(final String vendor, final String ret) {

                }
            });
            umVerifyHelper.removeAuthRegisterXmlConfig();
            umVerifyHelper.removeAuthRegisterViewConfig();
            umVerifyHelper.setAuthUIConfig(new UMAuthUIConfig.Builder()
                    .setNavHidden(true)
                    .setLogoImgPath("new_icon")
                    .setLogoWidth(67)
                    .setLogoHeight(67)
                    .setLogoOffsetY(128)
                    .setLogBtnBackgroundPath("cycle_red")
                    .setSloganText(" ")
                    .setNumberColor(Color.parseColor("#303030"))
                    .setNumberSize(16)
                    .setNumFieldOffsetY(224)
                    .setLogBtnText("本机号码一键登录")
                    .setLogBtnOffsetY(258)
                    .setLogBtnTextColor(Color.parseColor("#ffffff"))
                    .setLogBtnTextSize(14)
                    .setLogBtnHeight(43)
                    .setLogBtnMarginLeftAndRight(50)
                    .setSwitchAccText(" ")
                    .setPrivacyState(false)
                    .setVendorPrivacyPrefix("《")
                    .setVendorPrivacySuffix("》")
                    .setPrivacyBefore("我已阅读并同意")
                    .setAppPrivacyOne("《豆花用户协议》",getPrivacyOne())
                    .setAppPrivacyTwo("《隐私政策》",getPrivacyTwo())
                    .setAppPrivacyColor(Color.parseColor("#666666"),Color.parseColor("#fe6e6e"))
                    .setPrivacyTextSize(11)
                    .setPrivacyOffsetY_B(44)
                    .create());
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取用户协议
     * @return
     */
    private String getPrivacyOne() {
        String str = "https://api.doufu.douhuayuedu.com/journal/detail?id=794";
        str = Constant.changeUrlHost(str);
        return str;
    }


    /**
     * 获取隐私政策
     * @return
     */
    private String getPrivacyTwo() {
        String str = "https://api.doufu.douhuayuedu.com/journal/detail?id=793";
        str = Constant.changeUrlHost(str);
        return str;
    }



    public void verifyLogin(boolean showLoadDialog) {
        if (AccountService.getInstance().isLogin()) {
            return;
        }
        try {
            if (showLoadDialog) {
                AppGlobalDialog.showDialog(mContext);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            verifyLogin();
        }

    }

    private void verifyLogin() {
        boolean isFirstInit = initVerify();
        View laySwitch = LayoutInflater.from(mContext).inflate(R.layout.view_uverify_custom_switch, null);
        View tvBtnSwitch = laySwitch.findViewById(R.id.tvBtnSwitch);
        tvBtnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                umVerifyHelper.hideLoginLoading();
                umVerifyHelper.quitLoginPage();
                jumpOtherLogin("");
            }
        });
        UMAuthRegisterViewConfig config = new UMAuthRegisterViewConfig.Builder().setRootViewId(UMAuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setView(laySwitch)
                .setCustomInterface(new UMCustomInterface() {
                    @Override
                    public void onClick(Context context) {

                    }
                })
                .build();
        umVerifyHelper.addAuthRegistViewConfig("custom_switch",config);
        if (isFirstInit) {
            Observable.timer(1500, TimeUnit.MILLISECONDS)
                    .compose(RxJavaHelper.<Long>observeOnMainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            isLoading = true;
                            umVerifyHelper.getLoginToken(mContext, 3000);
                        }
                    });
        }else{
            isLoading = true;
            umVerifyHelper.getLoginToken(mContext, 3000);
        }
    }


    public void verifyLogin(JSCallback callback) {
        this.callback = callback;
        verifyLogin(true);
    }


    public boolean verifyLoginFirstOpenApp() {
        boolean isFirstOpen = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SP_KEY_FIRST_OPEN_APP, mContext, true);
        if (isFirstOpen) {
            DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SP_KEY_FIRST_OPEN_APP,false,mContext);
            verifyLogin(false);
        }
        return isFirstOpen;
    }


}
